﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SCDL;
using System.IO;
using System.Xml;

namespace Sherwood.Utilities.ConfigurationSectionGenerator
{
    public partial class ConfigurationSectionGenerator : Form
    {
        public ConfigurationSectionGenerator()
        {
            InitializeComponent();
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            GenerateConfiguration();
        }

        private void GenerateConfiguration()
        {
            ScdlDocument document;
            string exampleXml = txtExample.Text;
            string language = rbCS.Checked ? "CS" : "VB";

            //Load XML
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(exampleXml);
                document = new ScdlDocument();
                document.LoadFromXml(doc);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }


            //Generate output
            StringBuilder outputCode = new StringBuilder();
            StringBuilder outputSchema =  new StringBuilder();
            TextWriter codeWriter = new StringWriter(outputCode);
            TextWriter schemaWriter = new StringWriter(outputSchema);
           
            try
            {
                new ConfigCodeGenerator().GenerateCode(document, language, codeWriter, txtCodeNamespace.Text);
                new ConfigSchemaGenerator().GenerateSchema(document, schemaWriter);
            }
            catch (Exception ex)
            {
                codeWriter.Dispose();
                schemaWriter.Dispose();
                MessageBox.Show(ex.Message);
                return;
            }
            codeWriter.Dispose();
            schemaWriter.Dispose();

            //Display
            txtCode.Text = outputCode.ToString();
            txtSchema.Text = outputSchema.ToString();

        }

        private void txtXmlNamespace_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnCopyCode_Click(object sender, EventArgs e)
        {
            txtCode.SelectAll();
            txtCode.Copy();
            txtCode.Select(0, 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtSchema.SelectAll();
            txtSchema.Copy();
            txtSchema.Select(0, 0);
        }
    }
}
